package com.soft.base.spring.redis;

import com.soft.base.contract.Session;
import com.soft.base.contract.SessionFacade;
import com.soft.base.exception.ParamException;
import com.soft.base.spring.util.Request;

import java.util.HashMap;
import java.util.Map;
/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
public class RedisSessionFacade implements SessionFacade {

    public RedisSessionFacade() {
        Session.boot(this);
    }

    @Override
    public String key() {
        if ( Request.request() == null) {
            return "";
        }
        String token = (String) Request.request().getAttribute("api-token");
        if (null == token) {
            token = (String) Request.request().getAttribute("authorization");
//            ParamException.throwException("api-token not set");
        }
        return String.format("api-token:%s", token);
    }

    @Override
    public String key(String token) {
        return String.format("api-token:%s", token);
    }

    @Override
    public <T> void set(String name, T value) {
        final String key = key();
        Map<String, Object> all = RedisUtil.getObject(key, Map.class);
        if (null == all) {
            all = new HashMap<>(1);
        }
        all.put(name, value);
        RedisUtil.setObject(key, all);
        RedisUtil.expire(key, 3600 * 24L);
    }

    @Override
    public Map<String, Object> all() {
        final String key = key();
        Map<String, Object> all = RedisUtil.getObject(key, Map.class);
        if (null == all) {
            all = new HashMap<>(1);
        }
        RedisUtil.expire(key, 3600 * 24L);
        return all;
    }

    @Override
    public <T> T get(String name) {
        final String key = key();
        Map<String, Object> all = RedisUtil.getObject(key, Map.class);
        if (null == all) {
            all = new HashMap<>(1);
        }
        RedisUtil.expire(key, 3600 * 24L);
        if (all.containsKey(name)) {
            return (T) all.get(name);
        }
        return null;
    }

    @Override
    public <T> T get(String name, String token) {
        String key = key(token);
        Map<String, Object> all = RedisUtil.getObject(key, Map.class);
        if (null == all) {
            all = new HashMap<>(1);
        }
        RedisUtil.expire(key, 3600 * 24L);
        if (all.containsKey(name)) {
            return (T) all.get(name);
        }
        return null;
    }

    @Override
    public void forget(String name) {
        final String key = key();
        Map<String, Object> all = RedisUtil.getObject(key, Map.class);
        if (null == all) {
            return;
        }
        if (all.containsKey(name)) {
            all.remove(name);
            RedisUtil.setObject(key, all);
            RedisUtil.expire(key, 3600 * 24L);
        }
    }
}
